package com.baseproject.rx.OnErrorHandler;

import android.text.TextUtils;

import com.baseproject.IRxSubscriberView;
import com.baseproject.datasource.ConfigParamsSubscriber;
import com.baseproject.util.LogUtils;
import com.baseproject.util.UserUtil;

import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import rx.Observable;

import static com.baseproject.appconfig.AppConfigBaseProject.REQUEST_CODE_NONE_LOGIN;
import static com.baseproject.appconfig.AppConfigBaseProject.REQUEST_CODE_NONE_ORDER;
import static com.baseproject.datasource.remote.RetryWhenProcess.MAX_RETRY_TIMES;

/**
 * 防止多个请求都返回需要登录时，重复打开登录页面。使用ConfigParams进行配置，针对不同的网络请求，分别设定是否回调打开登录页面
 * 统一回调流程：
 * 1：根据用户点击内容在BaseCallBackFragment中设置mPurpose，RxSubscriber和BaseCallBackPresenter中统一判断并根据mPurpose提示用户登录
 * 2：用户点击确认登录之后统一UIHelper中进行登录并设置回调requestcode为登录页面
 * 3：登录完成之后回到上一级页面，回调BaseCallBackFragment中的onActivityResult统一分发登录结果给上一级页面根据mPurpose进行后续操作
 */

public abstract class BaseErrorHandler {


    protected Throwable throwable;

    public abstract void handleError(ConfigParamsSubscriber configParamsSubscriber, IRxSubscriberView iRxSubscriberView, IErrorStateListener iErrorStateListener);

    public Observable<?> retry(int currentRetryTimes) {
        if (throwable instanceof UnknownHostException) {//网络开关关闭，无需耗电重试
            return Observable.error(throwable);
        }
        if (currentRetryTimes < MAX_RETRY_TIMES) {
            LogUtils.d("Repository", "delay retry by " + currentRetryTimes + " second(s)");
            return Observable.timer(currentRetryTimes, TimeUnit.SECONDS);
        }
        return Observable.error(throwable);// don't retry
    }

    public static BaseErrorHandler createErrorHandler(Throwable e) {
        String code = UserUtil.getCode(e);
        if (TextUtils.isEmpty(code)) {
            return new DefaultErrorHandler(e);
        }
        switch (code) {
            case REQUEST_CODE_NONE_LOGIN + "":
                return new NeedLoginErrorHandler(e);
            case REQUEST_CODE_NONE_ORDER + "":
                return new NeedOrderErrorHandler(e);
            default:
                return new DefaultErrorHandler(e);
        }
    }


}
